<template>
  <div>
    <SearchComponent v-model:searchKeyWord="searchKeyWord" />
    <div class="h-[calc(100vh-50px)] overflow-y-scroll cursor-pointer">
      <template v-if="session.SessionList.length != 0">
        <ContextMenu
          v-for="(item, index) of FilteredItem"
          :key="index"
          :class="[ActiveSession(item.sessionId), IsPinned(item)]"
          :content="item"
          :menu-list="SessionListMenu"
          @select="(event, MenuItem) => MenuItem.click(event, item)"
        >
          <component :is="RenderSession(item)"></component>
        </ContextMenu>
      </template>
      <template v-else>
        <div class="w-full h-full flex flex-col justify-center items-center text-xs text-fontDisable">暂时没有消息</div>
      </template>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, h, ref } from "vue";
import { ISession } from "@/types/session";
import { ChatType, MessageType } from "@/types/chat";
import { useChat } from "@/store/modules/chat";
import { useSession } from "@/store/modules/session";
import { useSessionMenu } from "@/hooks/useMenu.ts";
import SearchComponent from "@/components/Search/index.vue";
import ContextMenu from "@/components/ContextMenu/index.vue";
import SessionItemMessage from "../components/SessionItemMessage.vue";
import SessionItemFriendRequest from "../components/SessionItemFriendRequest.vue";

const chat = useChat();
const session = useSession();
const { SessionListMenu } = useSessionMenu();
const searchKeyWord = ref("");

const FilteredItem = computed(() => {
  if (!session.SessionList) return [];
  return session.SessionList.filter((item) => {
    if (item.chatType === ChatType.group) {
      return item.name.includes(searchKeyWord.value);
    }
    return item.name.includes(searchKeyWord.value);
  });
});
const ActiveSession = computed(() => {
  return function (sessionId: string) {
    if (!chat.ChatObject) return "";
    return sessionId === chat.ChatObject.sessionId ? "active" : "";
  };
});
const IsPinned = computed(() => {
  return (item: any) => (item.isPinned ? "bg-CenterHover" : "");
});

// 渲染sessionItem
function RenderSession(item: ISession) {
  switch (item.chatType) {
    case ChatType.friendNotify:
      if (item.sessionType === MessageType.requestAdd) {
        return h(SessionItemFriendRequest, { SessionItem: item });
      }
      break;
    default:
      return h(SessionItemMessage, { SessionItem: item });
  }
}

session.GetSessionChatList();
</script>

<style lang="scss" scoped>
.active {
  background-color: var(--bg-session-active);
}
</style>
